package com.daka.tools;

import lombok.Data;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author beliveli on 2016/5/11
 */
@Data
@SuppressWarnings("unused")
public class CheckLogin {
    private int manageId;
    private List<String> roleList;

    public static CheckLogin build(int manageId, String roles) {
        CheckLogin checkLogin = new CheckLogin();
        checkLogin.setManageId(manageId);

        List<String> roleList = CheckLogin.String2List(roles);

        checkLogin.setRoleList(roleList);

        return checkLogin;
    }

    public static boolean checkRole(HttpSession session, List<Integer> sourceList) {
        CheckLogin loginUser = CheckLogin.build(Integer.parseInt(session.getAttribute("userId").toString()), session.getAttribute("roles").toString());
        for (Integer source : sourceList) {
            //noinspection SuspiciousMethodCalls
            if (loginUser.getRoleList().contains("{"+source+"}")) {
                return true;
            }
        }

        return false;
    }

    public static List<Integer> String2IntList(String str) {
        String[] roleArray = str.split(",");
        List<Integer> roleList = new ArrayList<Integer>();
        for (String role : roleArray) {
            roleList.add(Integer.parseInt(role));
        }

        return roleList;
    }

    public static List<String> String2List(String str) {
        String[] roleArray = str.split(",");
        List<String> roleList = new ArrayList<String>();
        Collections.addAll(roleList, roleArray);

        return roleList;
    }
}
